package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    /*@SneakyThrows
    public boolean isExclude() {
        try {
            String requestURI = request.getRequestURI();
            if(requestURI.startsWith("/member")) {
                return false;
            }
            return true;
        } catch (Exception e) {
            //如果是定时任务或者AMQP消费消息，是没有request的，就会出现异常，针对这种情况，直接选择不填充即可或者给默认1都行
            return false;
        }
    }*/
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        // 自动填充创建人
//        if (isExclude()){}
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUser()));

        // 获取当前登录用户，如果没有则为系统默认值
        Long userId = UserThreadLocal.getUserId();
        if (userId != null && !isSystemTask()) {
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(userId));
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
//        if(isExclude()){}
            this.setFieldValByName("updateBy", String.valueOf(getLoginUser()), metaObject);

        // 获取当前登录用户，如果没有则为系统默认值
        Long userId = UserThreadLocal.getUserId();
        if (userId != null && !isSystemTask()) {
            this.setFieldValByName("updateBy", String.valueOf(userId), metaObject);
        }

//        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
//        this.strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(getLoginUser()));
    }

    public Long getLoginUser() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }

    /**
     * 判断是否是系统后台任务（如定时任务、异步任务等）
     * 可根据实际情况扩展判断方式
     */
    private boolean isSystemTask() {
        // 示例：通过线程名判断是否是 Quartz 任务线程
        String threadName = Thread.currentThread().getName();
        return threadName.contains("quartz") || threadName.contains("task-");
    }
}
